import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import okhttp3.internal.http.HttpCodec;

/**
 * @ClassName Server
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2021/11/14 下午11:12
 * @Version V1.0
 * @Since JDK 11
 */
public class Server {

    public static void main(String[] args) {
        EventLoopGroup boss = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors()*2);
        EventLoopGroup work = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors()*2);
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(boss,work).channelFactory(NioServerSocketChannel::new)
                .childOption(ChannelOption.SO_KEEPALIVE,false)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new HttpServerCodec())
                                .addLast(new HttpObjectAggregator(1024))
                                .addLast(new HttpHandler());
                    }
                });
        Channel channel = null;
        try {
            channel = serverBootstrap.bind(8801).channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
            if (channel != null) {
                channel.close();
            }
        }
    }
}
